package com.knezevic.realestate.pages;

import com.knezevic.realestate.Identifiable;
import com.knezevic.realestate.Member;
import com.knezevic.realestate.Privilege;
import com.knezevic.realestate.service.Members;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;

public class Login {

    @Inject
    private Members members;
    @Property
    @Persist
    private String username;
    @Property
    @Persist
    private String password;
    @InjectPage
    private Home home;
    @InjectPage
    private AdminHome adminHome;
    @Persist("flash")
    @Property
    private String message;
    private long ID;

    Object onSubmitFromLoginForm() {
        for (Member mem : members.retrieve()) {
            if (mem.getPassword().equalsIgnoreCase(password) && mem.getUsername().equalsIgnoreCase(username)) {
                if (mem.getPrivilege().equals(Privilege.ADMINISTRATOR)) {
                    ID = Identifiable.class.cast(mem).getID();
                    adminHome.setID(Identifiable.class.cast(mem).getID());
                    return adminHome;
                } else {
                    home.setID(Identifiable.class.cast(mem).getID());
                    return home;
                }

            }
        }
        message = "Wrong username or password! Please try again!";
        return null;
    }

    public long getID(){
        return ID;
    }
}
